package cqie.cn.frame.config;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cqie.cn.frame.entity.SysUser;
import cqie.cn.frame.service.ISysUserService;
import cqie.cn.frame.utils.JWTUtils;
import cqie.cn.frame.utils.RetJson;
import cqie.cn.frame.utils.RetJsonUtils;
import cqie.cn.frame.utils.StringHandler;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author 王林
 * @version 1.0
 * @date 2021-09-03 周五
 * @time 22:17
 * @description
 */
public class Test {
//    public static int getResult(int n) {
//        if (n < 0) {
//            return -1;
//        }
//        if (n == 0 || n == 1) {
//            return 1;
//        }
//        return getResult(n * (n - 1));
//
//    }
//
//    public static void main(String[] args) {
//
//        System.out.println(Test.getResult(5));
//    }

    public static void main(String[] args) {

        Map<String, Object> map = new HashMap<>();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 20);

        String token = JWT.create()
                .withHeader(map) //header
                .withClaim("userId", 1)  //payload
                .withClaim("userName", "wanglin")  //withClaim是能放一个，第二个会覆盖第一个
                .withExpiresAt(instance.getTime())  //指定令牌过期时间
                .sign(Algorithm.HMAC256("dwer@$##$#"));   //签名

        System.out.println(token);


        //创建验证对象--- 先判断是否是算法错误，后检验签名
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("dwer@$##$#")).build();

        DecodedJWT verify = jwtVerifier.verify(token);

        int userId = verify.getClaim("userId").asInt();   //取值 userid
        System.out.println(userId);
        String userName = verify.getClaim("userName").asString();  //取值 userName
        System.out.println(userName);
        Date expiresAt = verify.getExpiresAt();       //取过期时间
        System.out.println("过期时间：" + expiresAt);


    }


    /**
     * @author 王林
     * @version 1.0
     * @date 2021-09-10 周五
     * @time 12:30
     * @description
     */
    public static class LoginController {
        @Resource
        private ISysUserService userService;

        //登录
        @ApiOperation(value = "登录", notes = "")
        @PostMapping(value = "/login")
        public RetJson login(@RequestBody SysUser mo) {
            try {
                QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
                wrapper.eq("account", mo.getAccount());
                List<SysUser> userList = userService.list(wrapper);
                //验证账号
                if (userList.size() == 0) {
                    return RetJsonUtils.error("账号错误");
                }
                String token = null;
                boolean passwordRight = false;
                boolean statusRight = false;
                for (SysUser sysUser : userList) {
                    if (sysUser.getPassword().equals(StringHandler.EncodeMD5(mo.getPassword()))) {
                        passwordRight = true;
                        if (sysUser.getStatus() == 0) {
                            statusRight = true;
                            //采用 session 保存用户，根据上下文获取session
                            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                            HttpSession session = request.getSession();
    //                        若存在，则修改；若不存在，则存入
                            session.setAttribute("loginUser", sysUser);

                            // 生成JWT 令牌
                            Map<String, String> payload = new HashMap<>();
                            payload.put("account", mo.getAccount());
                            payload.put("password", mo.getPassword());

                            token = JWTUtils.getToken(payload);
                            break;
                        }
                    }
                }
                if (passwordRight == false) {
                    return RetJsonUtils.error("登录密码错误");
                }
                if (statusRight == false) {
                    return RetJsonUtils.error("用户已禁用");
                }
                return RetJsonUtils.success("登录成功", token);
            } catch (Exception e) {
                return RetJsonUtils.error(e.getMessage());
            }
        }
    }
}
